package org.example.new_hbps_backend_reconstruction.controller.patient;

import org.example.new_hbps_backend_reconstruction.common.results.R;
import org.example.new_hbps_backend_reconstruction.service.PatientDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author 丁利军
 * @date 2025年10月16日 11:31
 * @description 心永腕表配置控制器
 */

import com.alibaba.fastjson.JSONObject;
import org.example.new_hbps_backend_reconstruction.service.UserConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.new_hbps_backend_reconstruction.service.UserConfigService;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

/**
 * 患者设备（心永）静默测量与用户配置
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/patient/userDevice2Config")
@Tag(
        name = "患者心永设备-测量与配置",
        description = "设置白天/夜间静默测量间隔、静默测量白天时间段、开启/关闭自动测量，以及根据patientUid获取user_access_token等"
)
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
@Slf4j
public class UserDevice2ConfigController {

    private final UserConfigService userConfigService;

    // ========== 设置预标定 ==========
    @Operation(
            summary = "设置预标定",
            description = "调用心永【预标定】接口，发送血压和心率数据进行预标定"
    )
    @Parameters({
            @Parameter(name = "patientUid", description = "用户 patientUid", required = true),
            @Parameter(name = "sbp", description = "收缩压（SBP）", required = true),
            @Parameter(name = "dbp", description = "舒张压（DBP）", required = true),
            @Parameter(name = "hr", description = "心率（HR）", required = true)
    })
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "设置成功"),
            @ApiResponse(responseCode = "400", description = "参数错误", content = @Content(schema = @Schema(implementation = R.class))),
            @ApiResponse(responseCode = "401", description = "token 无效/过期"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @PostMapping("/setPreCalibration")
    public R<?> setPreCalibration(@RequestParam Long patientUid,
                                  @RequestParam int sbp, @RequestParam int dbp, @RequestParam int hr) {
        log.info("设置预标定数据 sbp={}, dbp={}, hr={}", sbp, dbp, hr);
        return userConfigService.setPreCalibration(patientUid, sbp, dbp, hr);
    }

    // ========== 设置白天静默测量间隔 ==========
    @Operation(
            summary = "设置白天静默测量间隔",
            description = "调用心永【新增/修改个人配置】接口，设置白天静默测量间隔（单位：秒）。" +
                    "value 固定为 0 表示开启，property 为间隔秒数（文档最小 300s）。"
    )
    @Parameters({
            @Parameter(name = "user_access_token", description = "用户 access token（来自 4.3 接口）", required = true),
            @Parameter(name = "intervalSeconds", description = "白天静默测量间隔（秒），示例：1800", required = true)
    })
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "设置成功"),
            @ApiResponse(responseCode = "400", description = "参数错误", content = @Content(schema = @Schema(implementation = R.class))),
            @ApiResponse(responseCode = "401", description = "token 无效/过期"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @PostMapping("/setDaytimeInterval")
    public R<?> setDaytimeInterval(@RequestHeader("user_access_token") String userAccessToken,
                                   @RequestParam int intervalSeconds) {
        log.info("设置白天静默间隔 intervalSeconds={}", intervalSeconds);
        return userConfigService.setDaytimeInterval(userAccessToken, intervalSeconds);
    }

    // ========== 设置夜间静默测量间隔 ==========
    @Operation(
            summary = "设置夜间静默测量间隔",
            description = "调用心永【新增/修改个人配置】接口，设置夜间静默测量间隔（单位：秒）。" +
                    "value 固定为 0 表示开启，property 为间隔秒数（文档最小 300s）。"
    )
    @Parameters({
            @Parameter(name = "user_access_token", description = "用户 access token（来自 4.3 接口）", required = true),
            @Parameter(name = "intervalSeconds", description = "夜间静默测量间隔（秒），示例：1800", required = true)
    })
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "设置成功"),
            @ApiResponse(responseCode = "400", description = "参数错误"),
            @ApiResponse(responseCode = "401", description = "token 无效/过期"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @PostMapping("/setNightInterval")
    public R<?> setNightInterval(@RequestHeader("user_access_token") String userAccessToken,
                                 @RequestParam int intervalSeconds) {
        log.info("设置夜间静默间隔 intervalSeconds={}", intervalSeconds);
        return userConfigService.setNightInterval(userAccessToken, intervalSeconds);
    }

    // ========== 设置白天时间段 ==========
    @Operation(
            summary = "设置静默测量白天时间段",
            description = "设置静默测量的白天时间范围（小时，整点）。不在该范围内视为夜间。示例：startHour=6, endHour=22。"
    )
    @Parameters({
            @Parameter(name = "user_access_token", description = "用户 access token（来自 4.3 接口）", required = true),
            @Parameter(name = "startHour", description = "白天开始整点，范围 0-23，示例：6", required = true),
            @Parameter(name = "endHour", description = "白天结束整点，范围 0-23，示例：22", required = true)
    })
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "设置成功"),
            @ApiResponse(responseCode = "400", description = "参数错误"),
            @ApiResponse(responseCode = "401", description = "token 无效/过期"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @PostMapping("/setDaytimeRange")
    public R<?> setDaytimeRange(@RequestHeader("user_access_token") String userAccessToken,
                                @RequestParam String startHour,
                                @RequestParam String endHour) {
        log.info("设置白天时间段 {}-{}", startHour, endHour);
        return userConfigService.setDaytimeRange(userAccessToken, startHour, endHour);
    }

    // ========== 开/关 自动测量总开关 ==========
    @Operation(
            summary = "开启/关闭自动测量（总开关）",
            description = "统一控制白天与夜间两个静默测量配置的 value（0 开启、1 关闭）。" +
                    "可同时指定默认间隔秒数（未传则默认 1800s）。"
    )
    @Parameters({
            @Parameter(name = "user_access_token", description = "用户 access token（来自 4.3 接口）", required = true),
            @Parameter(name = "enable", description = "true 开启，false 关闭", required = true),
            @Parameter(name = "intervalSeconds", description = "默认间隔秒数，未传默认 1800")
    })
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "操作成功"),
            @ApiResponse(responseCode = "400", description = "参数错误"),
            @ApiResponse(responseCode = "401", description = "token 无效/过期"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @PostMapping("/switchAutoMeasure")
    public R<?> switchAutoMeasure(@RequestHeader("user_access_token") String userAccessToken,
                                  @RequestParam boolean enable,
                                  @RequestParam(defaultValue = "1800") int intervalSeconds) {
        log.info("切换自动测量 enable={}, intervalSeconds={}", enable, intervalSeconds);
        return userConfigService.switchAutoMeasure(userAccessToken, enable, intervalSeconds);
    }

    // ========== 根据 uid 获取 user_access_token ==========
    @Operation(
            summary = "根据 patientUid 获取 user_access_token",
            description = "服务端根据 patientUid 调用心永 4.3 接口换取 user_access_token（有效期 2 小时）。"
    )
    @Parameters({
            @Parameter(name = "uid", description = "患者 patientUid", required = true)
    })
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "获取成功"),
            @ApiResponse(responseCode = "400", description = "参数错误"),
            @ApiResponse(responseCode = "404", description = "未注册/找不到设备"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @GetMapping("/userAccessToken/{uid}")
    public R<?> getUserAccessTokenByUid(@PathVariable("uid") Long uid) {
        log.info("根据 uid 获取 user_access_token, uid={}", uid);
        return userConfigService.getUserAccessTokenByUid(uid);
    }
    @Operation(
            summary = "设置静默（勿扰模式）测量模式",
            description = """
                    设置静默测量所采用的模式并开启/关闭。
                    - key: silent_measurement_ppg_enabled
                    - value: 0 开启、1 关闭
                    - property: 0 脉搏波(PPG)，1 示波法
                    """
    )
    @Parameters({
            @Parameter(name = "user_access_token", description = "用户 access token（来自 4.3 接口）", required = true),
            @Parameter(name = "enable", description = "是否开启静默测量模式：true 开启 / false 关闭", required = true),
            @Parameter(name = "method", description = "静默测量算法：0=脉搏波(PPG)，1=示波法", required = true)
    })
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "设置成功"),
            @ApiResponse(responseCode = "400", description = "参数错误", content = @Content(schema = @Schema(implementation = R.class))),
            @ApiResponse(responseCode = "401", description = "token 无效/过期"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @PostMapping("/setSilentMode")
    public R<?> setSilentMode(@RequestHeader("user_access_token") String userAccessToken,
                              @RequestParam boolean enable,
                              @RequestParam Integer method) {
        log.info("设置静默测量模式 enable={}, method={}", enable, method);
        return userConfigService.setSilentMode(userAccessToken, enable, method);
    }
    // ========== 设置静默测量白天是否加压 ==========
    @Operation(
            summary = "设置静默测量-白天是否加压",
            description = "设置静默测量（白天）是否加压：property=0 不加压，1 加压；value 固定传 0 以启用。"
    )
    @Parameters({
            @Parameter(name = "user_access_token", description = "用户 access token（来自 4.3 接口）", required = true),
            @Parameter(name = "pressurize", description = "是否加压：true=加压，false=不加压", required = true)
    })
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "设置成功"),
            @ApiResponse(responseCode = "400", description = "参数错误", content = @Content(schema = @Schema(implementation = R.class))),
            @ApiResponse(responseCode = "401", description = "token 无效/过期"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @PostMapping("/setDaytimePressurize")
    public R<?> setDaytimePressurize(@RequestHeader("user_access_token") String userAccessToken,
                                     @RequestParam boolean pressurize) {
        log.info("设置静默测量白天是否加压 pressurize={}", pressurize);
        return userConfigService.setDaytimePressurize(userAccessToken, pressurize);
    }

    // ========== 设置静默测量夜间是否加压 ==========
    @Operation(
            summary = "设置静默测量-夜间是否加压",
            description = "设置静默测量（夜间）是否加压：property=0 不加压，1 加压；value 固定传 0 以启用。"
    )
    @Parameters({
            @Parameter(name = "user_access_token", description = "用户 access token（来自 4.3 接口）", required = true),
            @Parameter(name = "pressurize", description = "是否加压：true=加压，false=不加压", required = true)
    })
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "设置成功"),
            @ApiResponse(responseCode = "400", description = "参数错误", content = @Content(schema = @Schema(implementation = R.class))),
            @ApiResponse(responseCode = "401", description = "token 无效/过期"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @PostMapping("/setNightPressurize")
    public R<?> setNightPressurize(@RequestHeader("user_access_token") String userAccessToken,
                                   @RequestParam boolean pressurize) {
        log.info("设置静默测量夜间是否加压 pressurize={}", pressurize);
        return userConfigService.setNightPressurize(userAccessToken, pressurize);
    }

    // ========== 查询个人配置 ==========
    @Operation(
            summary = "查询个人配置列表",
            description = "调用心永接口 /api/ext/listUserConfig，读取当前用户的所有配置项（key/value/property）。"
    )
    @Parameters({
            @Parameter(name = "user_access_token", description = "用户 access token（来自 4.3 接口）", required = true)
    })
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "400", description = "参数错误", content = @Content(schema = @Schema(implementation = R.class))),
            @ApiResponse(responseCode = "401", description = "token 无效/过期"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @PostMapping("/listUserConfigs")
    public R<?> listUserConfigs(@RequestHeader("user_access_token") String userAccessToken) {
        log.info("查询个人配置列表");
        return userConfigService.listUserConfigs(userAccessToken);
    }

}